var showTimerId;
var hideTimerId;
var rebang;
var html;
var anchorX;

if (self == top) {
  chrome.extension.onConnect.addListener(function(port) {
    console.assert(port.name == "googleRebang");
    port.onMessage.addListener(onMessageReceived);
  });
  document.addEventListener('mouseover', function(e) {
    hide(400);
  }, false);
}

function onMessageReceived(data) {
  if (data.message == "show") {
    html = data.html;
    anchorX = data.anchorX;
    show(300);
  } else if (data.message == "hide") {
    hide(600);
  }
}

function show(delay) {
  window.clearTimeout(hideTimerId);
  hideTimerId = null;
  if (showTimerId) return;
  if (rebang) {
    fadeIn();
    return;
  }
  showTimerId = window.setTimeout(function() {
    rebang = getRebangElement();
    document.body.appendChild(rebang);
    showTimerId = null;
    fadeIn();
  }, delay);
}

function hide(delay) {
  window.clearTimeout(showTimerId);
  showTimerId = null;
  if (!rebang || hideTimerId) return;
  hideTimerId = window.setTimeout(function() {
    fadeOut();
  }, delay);
}

function getRebangElement() {
  var rebang = document.createElement('div');
  rebang.setAttribute('id', 'googlerebang');
  rebang.innerHTML = html;
  rebang.style.position = 'fixed';
  rebang.style.zIndex = '9999';
  rebang.style.width = '185px';
  rebang.style.background = 'transparent';
  rebang.style.top = (document.defaultView.innerHeight - 267 - 25) + 'px';
  rebang.style.left = Math.max(0, anchorX - 185 / 2) + 'px';
  rebang.style.webkitBoxShadow = "5px 5px 5px #888";
  rebang.style.opacity = 0;
  rebang.onmouseover = function() {
    window.clearTimeout(hideTimerId);
    hideTimerId = null;
    event.stopPropagation();
    fadeIn();
  };
  rebang.onmouseout = function() { hide(400); };
  return rebang;
}

function fadeIn() {
  var value = parseFloat(rebang.style.opacity);
  if (value >= 1) return;
  var tt = window.setInterval(function() {
    value += 0.2;
    if (value < 1.0) {
      rebang.style.opacity = value + "";
    } else {
      rebang.style.opacity = '1';
      window.clearInterval(tt);
    }
  }, 40);
}

function fadeOut() {
  var value = parseFloat(rebang.style.opacity) - 0.2;
  if (value > 0) {
    rebang.style.opacity = value + "";
    hideTimerId = window.setTimeout(fadeOut, 40);
  } else {
    rebang.parentNode.removeChild(rebang);
    rebang = null;
    hideTimerId = null;
  }
}
